using System;
using System.Collections.Generic;
using Godot;

/*
* 服务端
*/
public partial class MultiplayerScene
{
    public List<Message> messages = new List<Message>();
    public Dictionary<long, Player> players = new Dictionary<long, Player>();
    public List<InGame> inGames = new List<InGame>();
    int roomcount = 0;

    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void MatchingGame(long id)
    {
        players[id].matching = true;
        GD.Print($"玩家:{players[id].name} 开始匹配");
    }
    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void SetCell(long id, int index)
    {
        int x = index / 3;
        int y = index - x * 3;
        Player player = players[id];
        InGame game = GetInGame(player);
        if (game != null)
        {
            if (game.roundChessman == player.chessman)
            {
                game.guid[x, y] = player.chessman;
                if (game.roundChessman == 1) game.roundChessman = 2;
                else game.roundChessman = 1;
            }
        }
    }
    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void SetPlayerName(long id, string name)
    {
        GD.Print($"id:{id} 设置名称");
        players[id].name = name;
    }
    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void SendGlobalMsg(long id, string str)
    {
        string name = "Server";
        if (id != 1) name = players[id].name;
        var msg = new Message()
        {
            time = System.DateTime.Now.ToString("HH时 mm分 ss秒"),
            name = name,
            msg = str
        };
        messages.Add(msg);
        Rpc("SetMessage", msg.ToString());
    }
    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void SendRoundMsg(long id, string str)
    {
        Player player = players[id];
        var s = new Message()
        {
            time = System.DateTime.Now.ToString("HH时 mm分 ss秒"),
            name = player.name,
            msg = str
        }.ToString();
        GetInGame(player).messages.Add(s);
    }
    [Rpc(MultiplayerApi.RpcMode.AnyPeer, CallLocal = true)]
    public void ExitRound(long id)
    {
        Player player = players[id];
        InGame inGame = GetInGame(player);
        inGame.playerA.ingame = false;
        inGame.playerB.ingame = false;
        inGames.Remove(inGame);
        RpcId(inGame.playerA.id, "TargetDisconnected");
        RpcId(inGame.playerB.id, "TargetDisconnected");
    }

    private InGame GetInGame(Player player)
    {
        for (int i = 0; i < inGames.Count; i++)
        {
            if (inGames[i].roomid == player.roomid)
            {
                if (inGames[i].playerA.id != player.id &&
                inGames[i].playerB.id != player.id
                )
                {
                    return null;
                }
                else
                    return inGames[i];
            }
        }
        return null;
    }
}